/* eslint-disable */
<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">姓名</label>
        <el-input
          v-model="query.bisZhsqSnryXm"
          clearable
          placeholder="姓名"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">身份证</label>
        <el-input
          v-model="query.bisZhsqSnrySfz"
          clearable
          placeholder="身份证"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">订单状态</label>
        <el-select
          v-model="query.status"
          class="filter-item"
          filterable
          placeholder="请选择"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option :label="'全部'" value="" />
          <el-option
            v-for="item in dict.wxpaystatus"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!--        <label class="el-form-item-label">支付时间</label>-->
        <!--        <el-date-picker v-model="query.payTime" type="datetime"  style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />-->
        <!--        <label class="el-form-item-label">退款时间</label>-->
        <!--        <el-date-picker v-model="query.refundTime" type="datetime"  style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />-->
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation v-show="false" :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="更新时间">
            <el-input v-model="form.updatedAt" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column label="序号" type="index" width="55" />
        <!--        <el-table-column prop="subMchind" label="子商户号" />-->
        <!--        <el-table-column prop="orderNo" label="商户订单号" />-->

        <el-table-column prop="bisZhsqSnryXm" label="姓名" />
        <el-table-column width="150px" prop="bisZhsqSnrySfz" label="身份证" />
        <el-table-column width="180px" prop="orderNo" label="订单号" />
        <el-table-column prop="status" label="订单状态">
          <template slot-scope="scope">
            {{ dict.label.wxpaystatus[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column width="130px" label="支付金额(元)">
          <template #default="{ row }">
            <!-- 将分转换为元并格式化为两位小数 -->
            {{ (row.amount / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column width="150px" prop="payTime" label="支付时间" />
        <el-table-column width="150px" prop="refundTime" label="退款时间" />
        <!--        <el-table-column prop="notifyData" label="微信支付回调数据" />-->
        <!--        <el-table-column prop="refundNotifyData" label="退款回调数据" />-->
        <el-table-column width="150px" prop="description" label="支付描述" />
        <el-table-column width="150px" prop="refundReason" label="退款原因" />

        <el-table-column width="150px" prop="createdAt" label="创建时间" />
        <el-table-column label="操作" width="180px" align="center">
          <template slot-scope="scope">
            <!-- 查询订单按钮 -->
            <el-button
              type="primary"
              size="mini"
              @click="handleQuery(scope.row)"
            >
              查询/修改
            </el-button>
            <!-- 退款按钮 -->
            <el-button
              v-if="scope.row.status == '1' "
              type="primary"
              size="mini"
              @click="handleRefund(scope.row)"
            >
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>

    <!-- 查询结果弹窗 -->
    <el-dialog :visible.sync="showQueryDialog" title="订单详情" width="600px">
      <!-- 表单部分 -->
      <el-form :model="queryResult" label-width="120px" size="small">
        <el-form-item label="当前订单状态" prop="status">
          <el-select v-model="nowOrder.status" style="width: 100%" filterable placeholder="请选择">
            <el-option
              v-for="item in dict.wxpaystatus"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 分割线和注释 -->
        <el-divider>微信订单信息</el-divider>
        <el-form-item label="交易状态">
          <el-row gutter="{20}" type="flex" justify="space-between">
            <!-- 输入框：当交易状态为 'REFUND' 时，输入框占 16 列，否则占 24 列 -->
            <el-col :span="queryResult.tradeState === 'REFUND' ? 18 : 24">
              <el-input v-model="tradeStateLabel" disabled />
            </el-col>
            <!-- 退款按钮：当交易状态为 'REFUND' 时显示，并且右对齐 -->
            <el-col
              v-if="queryResult.tradeState === 'REFUND'"
              :span="6"
              style="display: flex; justify-content: flex-end;"
            >
              <el-button size="small" type="primary" @click="queryRefundInfo">退款信息</el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="交易状态描述">
          <el-input v-model="queryResult.tradeStateDesc" disabled />
        </el-form-item>
        <el-form-item v-if="queryResult.bankType" label="银行类型">
          <el-input :value="queryResult.bankType == 'OTHERS' ? '非银行卡支付(余额/零钱通等)' : '银行卡支付:' + queryResult.bankType" disabled />
        </el-form-item>
        <el-form-item v-if="queryResult.successTime" label="支付完成时间">
          <el-input :value="formattedSuccessTime" disabled />
        </el-form-item>
        <el-form-item v-if="queryRefundResult.status" label="退款状态">
          <el-input :value="refundStatusLabel" disabled />
        </el-form-item>
        <el-divider v-if="queryRefundResult.status">微信订单退款信息</el-divider>
        <el-form-item v-if="queryRefundResult.channel" label="退款渠道">
          <el-input :value="channelLabel" disabled />
        </el-form-item>
        <el-form-item v-if="queryRefundResult.userReceivedAccount" label="退款入账账户">
          <el-input :value="queryRefundResult.userReceivedAccount" disabled />
        </el-form-item>
        <el-form-item v-if="queryRefundResult.successTime" label="退款成功时间">
          <el-input :value="formattedRefundSuccessTime" disabled />
        </el-form-item>
      </el-form>

      <!-- 底部按钮部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="showQueryDialog = false">关闭</el-button>
        <el-button type="primary" @click="changeOrderStatus">变更订单状态</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import crudJjzhWxPayOrders from '@/api/business/jjzhWxPayOrders'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import { refund, query, queryRefund } from '@/api/business/jjzhWxPayOrders'
import { updateOrdersStatus } from '../../../api/business/jjzhWxPayOrders'

const tradeStateMap = {
  SUCCESS: '支付成功',
  REFUND: '转入退款',
  NOTPAY: '未支付',
  CLOSED: '已关闭',
  REVOKED: '已撤销（仅付款码支付会返回）',
  USERPAYING: '用户支付中（仅付款码支付会返回）',
  PAYERROR: '支付失败（仅付款码支付会返回）'
}
const refundChannelMap = {
  ORIGINAL: '原路退款',
  BALANCE: '退回到余额',
  OTHER_BALANCE: '原账户异常退到其他余额账户',
  OTHER_BANKCARD: '原银行卡异常退到其他银行卡'
}

const refundStatusMap = {
  SUCCESS: '退款成功',
  CLOSED: '退款关闭',
  PROCESSING: '退款处理中',
  ABNORMAL: '退款异常，可前往服务商平台-交易中心，手动处理此笔退款'
}

const defaultForm = {
  wxPayOrdersId: null,
  bisZhsqId: null,
  subMchind: null,
  orderNo: null,
  transactionId: null,
  amount: null,
  description: null,
  refundReason: null,
  bisZhsqSnryXm: null,
  bisZhsqSnrySfz: null,
  currency: null,
  status: null,
  payTime: null,
  refundTime: null,
  notifyData: null,
  refundNotifyData: null,
  createdAt: null,
  updatedAt: null
}
export default {
  name: 'JjzhWxPayOrders',
  components: { pagination, crudOperation, rrOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['wxpaystatus'],
  cruds() {
    return CRUD({
      query: { status: '1' },
      title: '居家照护微信支付订单',
      url: 'api/jjzhWxPayOrders',
      idField: 'wxPayOrdersId',
      sort: 'wxPayOrdersId,desc',
      crudMethod: { ...crudJjzhWxPayOrders }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'jjzhWxPayOrders:add'],
        edit: ['admin', 'jjzhWxPayOrders:edit'],
        del: ['admin', 'jjzhWxPayOrders:del']
      },
      rules: {},
      queryResult: {},
      queryRefundResult: {},
      showQueryDialog: false,
      loadingInstance: null,
      nowOrder: {},
      queryTypeOptions: [
        { key: 'bisZhsqSnryXm', display_name: '姓名' },
        { key: 'bisZhsqSnrySfz', display_name: '身份证' },
        { key: 'status', display_name: '订单状态' },
        { key: 'payTime', display_name: '支付时间' },
        { key: 'refundTime', display_name: '退款时间' }
      ]
    }
  },
  computed: {
    // 将 tradeState 映射为对应的中文状态
    tradeStateLabel() {
      return tradeStateMap[this.queryResult.tradeState] || this.queryResult.tradeState
    },
    formattedSuccessTime() {
      if (!this.queryResult.successTime) return ''
      const date = new Date(this.queryResult.successTime)
      return date.toLocaleString() // 格式化为当地时间的字符串
    },
    formattedRefundSuccessTime() {
      if (!this.queryRefundResult.successTime) return ''
      const date = new Date(this.queryRefundResult.successTime)
      return date.toLocaleString() // 格式化为当地时间的字符串
    },
    channelLabel() {
      return refundChannelMap[this.queryRefundResult.channel] || this.queryRefundResult.channel
    },
    refundStatusLabel() {
      return refundStatusMap[this.queryRefundResult.status] || this.queryRefundResult.status
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 退款方法
    handleRefund(row) {
      console.log(row)
      this.$confirm('确认要退款吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 开启loading
        this.loadingInstance = this.$loading({
          lock: true,
          text: '退款申请中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        // 调用退款接口
        refund(row.orderNo).then(res => {
          console.log(res)
          this.$message.success(res)
          // 刷新数据或更新状态
          this.crud.toQuery()
        }).catch(err => {
          this.$message.error('退款失败: ' + err.message)
        }).finally(() => {
          // 请求完成后关闭loading
          this.loadingInstance.close()
        })
      }).catch(() => { /* 取消不做操作 */
      })
    },
    // 查询订单
    handleQuery(row) {
      this.queryRefundResult = {}
      this.queryResult = {}
      console.log(row)
      row.status = String(row.status)
      this.nowOrder = row
      // 开启loading
      this.loadingInstance = this.$loading({
        lock: true,
        text: '正在查询...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      // 调用退款接口
      query(row.orderNo).then(res => {
        console.log(res)
        this.queryResult = res
        // 显示弹窗
        this.showQueryDialog = true
      }).catch(err => {
        this.$message.error('查询失败: ' + err.message)
      }).finally(() => {
        // 请求完成后关闭loading
        this.loadingInstance.close()
      })
    },
    // 变更订单状态的接口
    changeOrderStatus() {
      // 确认修改状态
      this.$confirm('确认要变更订单状态吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrdersStatus(this.nowOrder.orderNo, this.nowOrder.status).then(res => {
          this.$message.success('订单状态修改成功！')
        }).catch(err => {
          this.$message.error('订单状态修改失败: ' + err.message)
        }).finally(() => {
          this.showQueryDialog = false
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    queryRefundInfo() {
      // 显示弹窗
      // 开启loading
      this.loadingInstance = this.$loading({
        lock: true,
        text: '正在查询...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      queryRefund(this.nowOrder.orderNo).then(res => {
        console.log(res)
        this.queryRefundResult = res
      }).catch(() => {
        // 查询失败
      }).finally(() => {
        // 请求完成后关闭loading
        this.loadingInstance.close()
      })
    }
  }
}
</script>

<style scoped>
/* 自定义样式，可以根据需要修改 */
.el-divider {
  margin: 20px 0; /* 分割线的上下间距 */
}
</style>
